package com.applink.sell_proof.fragment;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Observable;
import java.util.Observer;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.applink.sell_proof.BasePagerActivity;
import com.applink.sell_proof.R;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.DataResult;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.builder.ProgramBuilder;
import com.applink.sell_proof.model.Program;

public class RewardCatalogFragment extends SherlockFragment implements Observer, OnItemSelectedListener{
	
	protected ViewGroup mLayout;
	private int mReferenceLoading = 3;
	private boolean mFlagInitialSelectedSpinner;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(mLayout == null){
			mLayout = (ViewGroup) inflater.inflate(R.layout.reward_catelog, null, false);
		}
		View header = inflater.inflate(R.layout.header_reward_catalog, null);
		((ListView)mLayout.findViewById(android.R.id.list)).addHeaderView(header, null, false);
		((Spinner)mLayout.findViewById(R.id.spinner_program)).setOnItemSelectedListener(this);
		setHasOptionsMenu(true);
		return mLayout;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		DataHelper.getInstance().addObserver(this);
		DataHelper.getInstance().getListProgramType();
		mReferenceLoading = 3;
		((BasePagerActivity)getActivity()).showProgressDialog(R.id.reward_catalog_container_loading);
	}
	
	@Override
	public void onPause() {
		super.onPause();
		DataHelper.getInstance().deleteObserver(this);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void update(Observable observable, Object data) {
		if(data == null) return;
		DataResult result = (DataResult) data;
		if(result.getMethodName() == Methods.getAllCampaign){
			Log.e("catalog", "get all campaign");
			mReferenceLoading--;
			if(mReferenceLoading == 0) ((BasePagerActivity)getActivity()).hideProgressDialog(R.id.reward_catalog_container_loading);
			if(result.getData() != null) {
				List<Entry<Long, String>> campaigns = (List<Entry<Long, String>>) result.getData();
				ArrayAdapter<Entry<Long, String>> adapter_campaign = new ArrayAdapter<Entry<Long, String>>(getActivity(),
						R.layout.spinner_item, campaigns);
				((Spinner)mLayout.findViewById(R.id.spinner_program)).setAdapter(adapter_campaign);
				((Spinner)mLayout.findViewById(R.id.spinner_program)).setSelection(0);
				mFlagInitialSelectedSpinner = true;
				
				getProgramAndSummary(campaigns.get(0).getKey(),campaigns.get(0).getValue());
			}
		} else if(result.getMethodName() == Methods.getAllProgramByCompaign){
			Log.e("catalog", "get all program");
			mReferenceLoading--;
			if(mReferenceLoading == 0) ((BasePagerActivity)getActivity()).hideProgressDialog(R.id.reward_catalog_container_loading);
			if(result.getData() != null) {
				List<Program> programs = (List<Program>) result.getData();
				ProgramBuilder builder = new ProgramBuilder(getActivity(), mLayout);
				builder.setData(programs);
			}
		} else if(result.getMethodName() == Methods.getEarnedRewardByCampaign){
			Log.e("catalog", "get earn reward");
			mReferenceLoading--;
			if(mReferenceLoading == 0) ((BasePagerActivity)getActivity()).hideProgressDialog(R.id.reward_catalog_container_loading);
			if(result.getData() != null) {
				Map<String, Integer> summary = (Map<String, Integer>) result.getData();
				((TextView)mLayout.findViewById(R.id.totalearned)).setText(Integer.toString(summary.get("Total")));
				((TextView)mLayout.findViewById(R.id.totalredeem)).setText(Integer.toString(summary.get("Redeemed")));
				((TextView)mLayout.findViewById(R.id.totalbalance)).setText(Integer.toString(summary.get("Balance")));
			}
		}
	}
	
	
	private void getProgramAndSummary(long campaignId,String campaignName) {
		DataHelper.getInstance().getEarnedRewardByCampaing(campaignId);
		DataHelper.getInstance().getListProgramByCampaing(campaignId,campaignName);
	}


	@Override
	public void onItemSelected(AdapterView<?> adapterView, View arg1, int position, long arg3) {
		if(mFlagInitialSelectedSpinner) {
			mFlagInitialSelectedSpinner = !mFlagInitialSelectedSpinner;
			return;
		}
		@SuppressWarnings("unchecked")
		long campaignId = ((Map.Entry<Long, String>)adapterView.getAdapter().getItem(position)).getKey();
		String campaignName = ((Map.Entry<Long, String>)adapterView.getAdapter().getItem(position)).getValue();
		getProgramAndSummary(campaignId,campaignName);
		mReferenceLoading = 2;
		((BasePagerActivity)getActivity()).showProgressDialog(R.id.reward_catalog_container_loading);
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		
	}
	
}
